﻿
using System.Collections.Generic;
using System.Data;
using Channelvn.Cached;
using Core.Library;
using DataObject.Ref;

namespace DataObject.Vote
{
    public class VoteController
    {
        /***************************************
        = Front End
        -------------------------------------- */

        internal static List<VoteLogObject> Vote_GetVoteLogByFromID(int id)
        {
            return ObjectHelper.MapRecords<VoteLogObject>(VoteDAL.Vote_GetVoteLogByFromID(id, RefCache.Ref_GetCurrentRound()));
        }

        public static void Vote_AddVoteLogToCache(VoteLogObject o)
        {
            var lst = VoteCache.Vote_GetVoteLogByFromID(o.VoteLog_FromID) ?? new List<VoteLogObject>();
            lst.Add(o);

            // add cache VoteLog
            var listParams = new object[] { o.VoteLog_FromID };
            var cacheName = CacheHelper.CacheKey.GetCacheKey("Vote_GetVoteLogByFromID", listParams);
            CacheController.Add(Constants.VOTE_CACHE_CATEGORY, cacheName, lst, Constants._15min);

            // add vote member
            var vote = VoteCache.Members_GetVoteByRound(o.VoteLog_ToID, o.VoteLog_Round) + 1;
            listParams = new object[] { o.VoteLog_ToID, o.VoteLog_Round };
            cacheName = CacheHelper.CacheKey.GetCacheKey("Members_GetVoteByRound", listParams);
            CacheController.Add(Constants.VOTE_CACHE_CATEGORY, cacheName, vote, Constants._15min);

            // add check is vote
            listParams = new object[] { o.VoteLog_FromID, o.VoteLog_ToID };
            cacheName = CacheHelper.CacheKey.GetCacheKey("Vote_CheckIsVoteMemberId", listParams);
            CacheController.Add(Constants.VOTE_CACHE_CATEGORY, cacheName, true, Constants._5min);
        }

         public static int Members_GetVoteByRound(int id, int round)
         {
             DataTable dt = null;
             using (var db = new MainDB())
             {
                 dt = db.StoredProcedures.Members_GetVoteByRound(id, (int)MemberStatus.IsPublished, round);
             }

             if (dt != null && dt.Rows.Count > 0)
                 return ConvertUtility.ConvertTo<int>(dt.Rows[0][0]);
             return 0;
         }
    }
}
